const fs = require('fs')
const path = require('path')
const template = require('art-template')
const md = require('markdown-it')()
const matter = require('gray-matter')
const glob = require('glob')

exports.renderPost = (filePath) => {
  // 读取 md 文件内容
  const mdContent = fs.readFileSync(filePath, 'utf8')

  const { data: meta, content } = matter(mdContent)

  // 将 md 转换为 html
  const htmlContent = md.render(content)

  return template(path.join(process.cwd(), './themes/default/post.html'), {
    content: htmlContent,
    meta
  })
}

exports.renderIndex = () => {
  const posts = []
  const paths = glob.sync('./_posts/**/*.md')
  for (let i = 0; i < paths.length; i++) {
    const filePath = paths[i]
    // 读取 md 文件内容
    const mdContent = fs.readFileSync(filePath, 'utf8')

    const { data: meta } = matter(mdContent)
    const url = exports.parseUrl(filePath)
    posts.push({
      meta,
      url
    })
  }
  return template(path.join(process.cwd(), './themes/default/index.html'), {
    posts
  })
}

exports.parseUrl = (filePath) => {
  const pathObj = path.parse(filePath.split('./_posts/')[1])
  const url = path
    .join('/', 'posts', pathObj.dir, `${pathObj.name}.html`)
    .split(path.sep)
    .join('/')
  return url
}
